<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>通过css的三个属性实现轮播图效果</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        body {
            height: 100%;
            width: 100%;
        }
        .container {
            display: flex;
            overflow: auto;
            height: 150px;
            margin: 20px;
            border-radius: 10px;
            scroll-snap-type: x mandatory;
            scroll-behavior: smooth;
        }

        .item-1,.item-2,.item-3 {
            min-width: 100%;
            background-position: center;
            background-size: cover;
            background-repeat: no-repeat;
            scroll-snap-align: start;
            cursor: pointer;
        }

        .item-1 {
            background-image: url(./image/img1.jpg);
        }
        .item-2 {
            background-image: url(./image/img2.jpg);
        }
        .item-3 {
            background-image: url(./image/img3.jpg);
        }

        .scrollbar::-webkit-scrollbar {
            width: 0 !important;
            height: 0;
        }
    </style>
</head>
<body>
    <div class="container scrollbar">
        <div class="item-1"></div>
        <div class="item-2"></div>
        <div class="item-3"></div>
    </div>

    <script>
        let box = document.querySelector('.container')
        let items = box.children
        let index = 0
        let timer = null

        function animate ()
        {
            timer = setInterval(() => {
                if (index > (items.length - 1))
                {
                    index = 0
                    box.scrollLeft = 0
                }
                else
                {
                    box.scrollLeft += items[index].offsetWidth
                    index++
                }
            }, 2000);
        }
        animate()

        box.addEventListener('mouseenter', function (){
            clearInterval(timer)
        })
        box.addEventListener('mouseleave', function () {
            animate()
        })
        box.addEventListener('touchstart', function (){
            clearInterval(timer)
        })
        box.addEventListener('touchend', function (){
            animate()
        })
    </script>
</body>
</html>
